<template>
  <div class="v-editor-NamedElement_name g-jc-sb">
    <div
      :class="{ _disable: disabled }"
      style="width: 100%; display: flex; justify-content: space-between"
    >
      <div
        v-if="isShowTerm && !isFocus && containTermName.length"
        class="g-pd-l-8"
        style="cursor: text; font-size: 12px"
        @click="handleTermClick"
      >
        <span
          v-for="(item, index) in containTermName"
          :key="index"
        >
          <span
            v-if="item.isTerm"
            class="show-underline"
            @contextmenu.stop="event => showDetailTerm(event, item.name)"
          >
            {{ item.name }}
          </span>
          <span v-else>{{ item.name }}</span>
        </span>
      </div>
      <el-input
        v-else
        id="nameElementProperty"
        ref="inputRef"
        v-model="inputvalue"
        class="g-one-line"
        type="textarea"
        :rows="1"
        :disabled="disabled"
        maxlength="100"
        style="padding: 3px"
        @change="handelChange"
        @focus="handleFocus"
        @blur="handleBlur"
      ></el-input>

      <div
        v-if="selected && !disabled"
        class="g-pd-r-4 img-btn"
      >
        <img
          src="statics/icons/app/iconmore.png"
          class="g-pointer"
          @click="handleClick"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { modelService } from "@/modules/model/service";
import { ref, computed, watch, inject, Ref, nextTick } from "vue";
import { propertyUtil } from "../../PropertyUtil";
import { PropertyRow } from "../../types";
import { BusEvent } from "@/constants/Enums";
import NamedElementName from "../modals/NamedElementName.vue";
import { desensitize } from "@/util/common";
import { actionManager } from "@/action/ActionManager";
import { ActionKey } from "@/action/ActionKey";
import { useKeyboardEvents } from "@/action/keyboardHandler";
import { ElInput } from "element-plus";
import { ContainTermName, splitOriginTextWithTerms } from "@/mdesign-lib/mdesign-graph.umd.js";
import { showDetailTermCommon } from "@/modules/model/service/termBankService";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

const emit = defineEmits<{
  (event: "quit-edit"): void;
}>();
/**
 * 单行输入框
 */
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
  encrypted?: boolean;
  isShowTerm?: boolean;
}>();

const isFocus = ref(false);

let inputvalue = ref<string>(props.encrypted ? desensitize(props.row.value) : (props.row.value as string));

const inputRef = ref<InstanceType<typeof ElInput>>();

const disabled = computed(() => {
  return props.row.readonly || isModelDisabled?.value || isRootProfile.value;
});

const isRootProfile = computed(() => {
  // 扩展包编辑，不允许修改正编辑的扩展包的名称
  if (app.activeProject?.config?.isProfile) {
    // 扩展包编辑，不允许修改正编辑的扩展包的名称
    const profileModelId = app.global.profileEditProjectIdMapModel.profileNameToProfileModelIdMap.get(
      app.activeProject?.config?.profileName
    ) as string;
    if (profileModelId === props.row.modelId) {
      return true;
    }
  }
  return false;
});

const containTermName = computed(() => {
  let _containTermName: ContainTermName[] = [];
  _containTermName = splitOriginTextWithTerms((props.row.value as string) || "", props.row.terms || []);
  return _containTermName;
});

watch(
  () => props.row.value,
  newVal => {
    inputvalue.value = props.encrypted ? desensitize(newVal) : (newVal as string);
  }
);

const handelChange = async () => {
  const dto = propertyUtil.getUpdatePropertyDtoByPropertyRow(props.row, app.activeProject!.id);
  dto.value = inputvalue.value;
  let res = await modelService.updateModelProperty({ ...dto, key: props.row.specificComponent || props.row.key });
  if (res) {
    app.$bus.emit(BusEvent.REFRESH_PROPERTY, props.row.modelId);
  }
  emit("quit-edit");
};

const handleFocus = () => {
  isFocus.value = true;
};
const handleBlur = () => {
  isFocus.value = false;
};
const handleTermClick = () => {
  if (disabled.value) return;
  isFocus.value = true;
  nextTick(() => {
    inputRef.value!.focus();
  });
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
let inModalEdit = false;

// function handleBlur() {
//   setTimeout(() => {
//     if (!inModalEdit) {
//       emit('quit-edit');

//     }
//   }, 200);
// }
function handleClick() {
  inModalEdit = true;
  NamedElementName.popup({
    row: props.row,
    disabled: disabled,
    encrypted: props.encrypted
  }).finally(() => {
    emit("quit-edit");
    inModalEdit = false;
  });
}

async function openChooseTerm() {
  const action = actionManager.getAction(ActionKey.chooseTerm);
  if (!action) return;
  await action.run("nameElementProperty", callback);
}
async function callback(scenario: string, term: string) {
  if (scenario === "nameElementProperty") {
    console.error("进入回调********nameElementProperty", term);

    inputRef.value!.focus();
    // inputvalue.value = term;
    document.execCommand("inserttext", false, term); // 直接inputvalue.value = term方式赋值后不会触发change事件，通过document.execCommand模拟光标位置插入动作
  }
}

function showDetailTerm(event: MouseEvent, termText: string) {
  showDetailTermCommon(event, termText);
}

useKeyboardEvents({
  "Ctrl+T": () => openChooseTerm()
});
</script>
<style lang="scss">
.v-editor-NamedElement_name {
  ._disable {
    background-color: #f5f7fa;
    color: #a8abb2 !important;
    cursor: not-allowed !important;
  }
  height: auto;
  min-height: 24px;
  // padding-left:5px;
  align-items: center;
  > .img-btn {
    display: flex;
    align-items: center;
  }
  .el-input .el-input__inner {
    padding-right: 0px;
  }

  .el-textarea__inner {
    resize: none;
    overflow: auto;
    text-overflow: ellipsis;
  }
  .el-textarea__inner:hover {
    box-shadow: none;
  }
}
</style>
